package com.lyncs.ods.modules.wx.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.MD5;
import com.lyncs.ods.common.api.CommonResult;
import com.lyncs.ods.config.WxMpConfiguration;
import com.lyncs.ods.constant.LyncsOdsConstant;
import com.lyncs.ods.modules.company.service.CompanyService;
import com.lyncs.ods.modules.user.service.UserService;
import com.lyncs.ods.req.WxInfoReq;
import com.lyncs.ods.req.WxMpLogin;
import com.lyncs.ods.utils.SpringUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author alex
 * @date 2022/1/28 15:49
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/auth/{appId}")
@Api(tags = {"微信授权相关接口"})
public class WxAuthController {

    @Autowired
    private UserService userService;
    @Autowired
    private CompanyService companyService;

    public static final String HOST = "https://ba29-116-6-234-242.ngrok.io";
    public static final String APP_ID = "wx5fbafb66272c83fa";

    /**
     * 获取微信登陆二维码地址
     *
     * @return
     */
    @ApiOperation(value = "获取微信登录二维码")
    @GetMapping("/getQRCodeUrl")
    @ApiResponses(@ApiResponse(code = 200, message = "返回url"))
    public CommonResult<String> getQRCodeUrl(@PathVariable String appId) {
        WxMpService wxMpService = WxMpConfiguration.getMpService(appId, WxMpServiceImpl.class);

        String date = DateUtil.format(new Date(), LyncsOdsConstant.Common.DATE_PATTERN);
        String state = MD5.create().digestHex(StringUtils.join(LyncsOdsConstant.Common.MD5_PREFIX, date));
        String qrConnectUrl = wxMpService.buildQrConnectUrl(StringUtils.join(HOST, "auth/", APP_ID, "/login"), "snsapi_login", state);
        log.info("getQRCodeUrl:{}", qrConnectUrl);
        return CommonResult.success(qrConnectUrl);
    }

    @GetMapping("/login")
    @ApiOperation(value = "微信扫码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "授权appId", dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "code", value = "授权code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "授权state", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "platform", value = "授权登录平台:weChatWebApp,weChatMiniApp。默认weChatWebApp", dataType = "String", paramType = "query"),
    })
    @ApiResponses(@ApiResponse(code = 200, message = "返回userId"))
    public CommonResult<String> login(@PathVariable String appId, @RequestParam String code, String state, @RequestHeader(required = false, defaultValue = "weChatWebApp") String platform) throws WxErrorException {
        return CommonResult.success(userService.login(appId, code, state, platform).toString());
    }

    @PostMapping("/mp/login")
    @ApiOperation(value = "微信小程序登录")
    @ApiResponses(@ApiResponse(code = 200, message = "返回userId"))
    public CommonResult<String> login(@PathVariable String appId, @RequestBody WxMpLogin wxMpLogin) throws WxErrorException {
        return CommonResult.success(userService.login(appId, wxMpLogin));
    }

    @PostMapping("/mp/phone")
    @ApiOperation(value = "微信小程序授权更新手机号")
    public CommonResult<?> savePhone(@PathVariable String appId, @RequestBody WxInfoReq wxInfoReq) throws WxErrorException {
        userService.savePhone(appId, wxInfoReq);
        return CommonResult.success();
    }

    @GetMapping("/{openId}")
    @ApiOperation(value = "获取调试token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "授权appid", dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "openId", value = "open_id", dataType = "String", paramType = "path")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "返回调试token"))
    public CommonResult<String> generateDebuggerToken(@PathVariable("appId") String appId, @PathVariable("openId") String openId) {
        if (SpringUtils.isProd()) {
            return null;
        }
        return CommonResult.success(userService.generateDebuggerToken(appId, openId));
    }

    @GetMapping("staff/join")
    @ApiOperation(value = "员工扫码加入，适用web端")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "授权appId", dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "company_id", value = "企业ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "微信授权Code", dataType = "String", paramType = "query"),
    })
    public CommonResult<?> staffJoin(@PathVariable String appId, @RequestParam("company_id") Long companyId, @RequestParam("code") String code) throws WxErrorException {
        companyService.staffJoin(appId, companyId, code);
        return CommonResult.success();
    }

}
